$def with (page, edition_loans, edition_ebook, user_loans, user_ip)

$var title: $page.title

$ _x = ctx.setdefault('bodyid', 'plain')

$ available_loans = page.get_available_loans()

$ current_and_available_loans = page.get_current_and_available_loans()
$ current_loans = current_and_available_loans[0]
$ loan_users = [loan['user'] for loan in current_loans]

$ pdf_resource_id = page.get_lending_resource_id('pdf')
$ epub_resource_id = page.get_lending_resource_id('epub')

$ meta_fields = page.get_ia_meta_fields()
$if meta_fields.has_key('contributor'):
    $ contrib = meta_fields['contributor']
$else:
    $ contrib = None

$ waitinglist = page.get_waitinglist()

$def format_users(users):
    $for user_key in users:
        $ user = user_key and get_document(user_key)
        $if user:
            <a href="$user.key" title="$user.key">$user.name</a>
        $else:
            <em>Unknown</em>

<style type="text/css">
ul.inner {
    margin-bottom: 0px !important;
}
</style>

<div id="contentHead">
    <div class="navBorrow">
        <a href="/" title="Return to home page"><img src="/images/logo_OL-sm.png" width="90" height="71" alt="Open Library logo" class="right"/></a>
        <a href="$page.url()"><strong>&larr; Back</strong></a>
    </div>

    <h1 class="sansserif">Borrow - Administration</h1>
</div>

<div id="contentBody">

        <div class="borrow">
            <table>
                <tbody>
                    <tr>
                        <td style="vertical-align:top;padding-right:10px;">
                            $:render_template('covers/book_cover_small', page)
                        </td>
                        <td>
                            <span class="book">
                                <a class="borrowResults" href="$page.url()"><strong>$page.title</strong></a>
                            </span>
                            <span class="author">
                            $ authors = page.works[0].get_authors()
                            $:macros.AuthorList(authors)
                            </span>
                            <br/>
                            <span class="publisher">
                            $if page.publish_date or page.publishers:
                                $if page.publish_date:
                                    $page.publish_date,
                                $else:
                                    <em>Published date unknown,</em>
                                $if page.publishers:
                                    $for p in page.publishers:
                                        $p$cond(loop.last, "", ", ")
                                $else:
                                    <em>publisher unknown</em>
                            </span>
                            $if contrib:
                                <span class="contributor small grey">
                                    from $contrib
                                </span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

    $ collections = page.get_ia_meta_fields()['collection']
    $if 'lendinglibrary' not in collections and 'inlibrary' not in collections:
        <div class="alert attn message" id="alert0">
            This book is not borrowable.
        </div>

    <div class="section">
        <h3>Current Loans</h3>
        $ borrow_status = get_borrow_status(page.ocaid)
        $if current_loans:
            $ loan = current_loans[0]
            <div id="borrowTable" class="borrow collapse current-loan">
            <table>
                <thead>
                    <tr>
                        <th class="xtitles">
                        $_("1 Current Loan")
                        </th>
                        <th class="expires">$_("Loan Expires")</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class="titles">
                            $ user = loan.get('user') and get_document(loan['user'])
                            $if user:
                                <a href="/admin$user.key">$user.name</a>
                            $else:
                                <em>Unknown</em>
                            <div class="date">
                                Borrowed $datestr(datetime_from_utc_timestamp(loan['loaned_at']))
                            </div>
                        </td>
                        <td class="expires">
                            $if loan['expiry'] is None:
                                $# Not yet fulfilled
                                <span class="red">Not yet downloaded. </span><br/>
                                <a href="$loan['loan_link']">Download Now</a>
                            $else:
                                $:macros.FormatExpiry(loan['expiry'])
                        </td>
                    </tr>
                </tbody>
            </table>
            </div>
        $elif borrow_status.checkedout_on_ia:
            <div class="checkedout-elsewhere">
                Checked out on Internet Archive.
            </div>
        $elif borrow_status.resource_epub == 'checkedout':
            <div class="checkedout-elsewhere">
                ACS4 server is showing that ePub is checked out.
            </div>
        $elif borrow_status.resource_pdf == 'checkedout':
            <div class="checkedout-elsewhere">
                ACS4 server is showing that ePub is checked out.
            </div>
        $elif not waitinglist:
            <div class="available">
                This title is available to borrow.
            </div>
        $else:
            <em>No current loans.</em>

        <div style="margin: 20px 0px;">
            <form method="POST">
                <input type="submit" value="Update loan info" />
                <input type="hidden" name="action" value="update_loan_info" />
            </form>
        </div>
    </div>

    <div class="section">
        <h3>Waiting List</h3>
        $if waitinglist:
            <div id="borrowTable" class="borrow collapse waitinglist">
            <table>
                <thead>
                    <tr>
                        <th class="xtitles" colspan="2">
                        $ungettext("%d person waiting", "%d people waiting", len(waitinglist), len(waitinglist))
                        </th>
                        <th class="status">Status</th>
                    </tr>
                </thead>
                <tbody>
                $for record in waitinglist:
                    $ u = record.get_user()
                    $ status = record['status']
                    <tr class="row-$status">
                        <td class="serial">$loop.index</td>
                        <td class="titles">
                            $if u:
                                <a href="/admin$u.key">$u.name</a>
                            $else:
                                $record['userid']
                            <div class="date">
                                $ ndays = record.get_waiting_in_days()
                                $ungettext("Waiting for %d day", "Waiting for %d days", ndays, ndays)
                                <div class="smaller gray">$record['since']</div>
                            </div>
                        </td>
                        <td class="status">
                            <span class="status-value">$record['status'].title()</span><br/>
                            $if status == "available":
                                $ delta_hours = record.get_expiry_in_hours()
                                <div class="smaller" style="padding-top: 5px;">
                                    $if delta_hours == 0:
                                        Less than an hour to borrow it.
                                    $elif delta_hours == 1:
                                        One more hour to borrow it.
                                    $else:
                                        $delta_hours more hours to borrow it.
                                </div>
                        </td>
                    </tr>
                </tbody>
            </table>
            </div>
        $else:
            <em>No one is waiting for this title.</em>
    </div>


    <div class="section">
        <h3>You</h3>
        <ul>
            <li>You are <a href="$ctx.user.key" title="$ctx.user.key">$ctx.user.displayname</a></li>
        </ul>
    </div>

    <div class="section">
        <h3>Borrow Info</h3>
        Borrowable? <em>$cond(page.in_borrowable_collection(), "Yes", "No")</em>
        <br/>
        $if loan_users:
          Borrowed by: $:format_users(loan_users)
        $else:
          Borrowed by: None
    </div>

    <div class="section">
        <h3>Borrow Status</h3>

        $ status = get_borrow_status(page.ocaid)
        <div>
        $if status.checkedout:
            <strong>Status: Not Available</strong>
        $else:
            <strong>Status: Available</strong>
        </div>
        <div>
            <strong>Reason:</strong>
            $if status.has_loan: Checkedout on OL
            $elif status.has_waitinglist: Some people are on the waiting list
            $elif status.checkedout_on_ia: Checkedout on IA
            $else: not checked out either on OL or IA
        </div>
        <br/>
        <div>Sources:
        <ul>
            <li>Open Library - $cond(status.has_loan, 'Checked out', 'Not checked out')$cond(status.has_waitinglist, ", but have people on waiting list", "")</li>
            <li>Internet Archive - $cond(status.checkedout_on_ia, 'Checked out', 'Not checked out')</li>
        </ul>
        </div>

        <div>Formats:
            <ul>
                <li>Bookreader - $status.resource_bookreader</li>
                <li>PDF - $status.resource_pdf</li>
                <li>ePub - $status.resource_epub</li>
            </ul>
        </div>
    </div>
    <div class="section">
        <h3>Book Info</h3>
        <ul>
            <li>key: <a href="$page.key">$page.key</a></li>
            <li>archive.org ID: <a href="//archive.org/details/$page.ocaid">$page.ocaid</a>
            <li>IA Collections:
                <ul class="inner">
                    $for c in page.get_ia_meta_fields()['collection']:
                        <li><span class="small">$c</span></li>
                </ul>
            </li>
            <li>external-identifiers from archive.org meta.xml
                <ul class="inner">
                $for x in page.get_lending_resources():
                    <li><span class="small">$x</span></li>
                </ul>
            </li>
            <li>OL Subjects
                <ul class="inner">
                    $for subject in page.works[0].get_subjects():
                        <li><span class="small">$subject</span></li>
                </ul>
            </li>
        </ul>
    </div>
    <div class="section">
        <h3>Available loans</h3>
        $if available_loans:
            $for loan in available_loans:
                <pre>$:json_encode(loan, indent="  ", sort_keys=True)</pre>
        $else:
            <em>None found</em>
    </div>
    <div class="section">
        <h3>Current loans</h3>
        $if edition_loans:
            $for loan in edition_loans:
                <div style="margin: 20px;">
                    <pre>$:json_encode(loan, indent="  ", sort_keys=True)
                    </pre>
                    <form method="POST">
                        <input type="submit" value="Delete this record" />
                        <input type="hidden" name="action" value="delete" />
                        <input type="hidden" name="loan_key" value="$loan['_key']" />
                    </form>
                </div>
        $else:
            <em>No current loans</em>
    </div>

    <div class="section">
        <h3>Edition ebook record from datastore</h3>
        <pre>$:json_encode(edition_ebook, indent="  ", sort_keys=True)</pre>
    </div>

    $def resource_info(urn):
        $ bss = 'http://lending.us.archive.org/bss/bss.py'
        <a href="$bss/is_loaned_out/$urn">Loan Status</a>
        | <a href="$bss/resource_info/$urn">Resource Info</a>
        | <a href="$bss/fulfillment_info/$urn">Fulfillment Info</a>

    <div class="section">
        <h3>Book status in ACS4</h3>
        <ul>
            <li>
                <p>
                PDF <span class="small gray">$pdf_resource_id</span><br/>
                $:resource_info(pdf_resource_id)
                </p>
            </li>
            <li>
                <p>
                ePub <span class="small gray">$epub_resource_id</span><br/>
                $:resource_info(epub_resource_id)
                </p>
            </li>
        </ul>
    </div>
    <div class="section">
        <h4>Waiting List JSON</h4>
        <pre>$:json_encode([doc.dict() for doc in waitinglist], indent=True)</pre>
    </div>
</div>


<style type="text/css">
body#plain #borrowTable {margin: 30px 0 25px;}
body#plain #borrowTable table {width:100%;font-family:"Lucida Grande","Arial",sans-serif;}
body#plain #borrowTable table th {
    border-bottom: 1px solid #c7c3b3;
    vertical-align: bottom;
    padding-bottom:10px;
    font-family:"News Gothic MT","Trebuchet MS",Geneva,Helvetica,sans-serif;
    color:#615132;
    font-weight:600;
    font-size:0.6875em;
    text-transform: uppercase;
    white-space: nowrap;
    text-align: center;
}

th.xtitles {
    text-align: left !important;
}

tr.row-available .status-value {
    color: darkgreen;
}

tr.row-available {
    background: #eeecad !important;
}


td.status, th.status {
    padding: 15px;
    text-align: center;
}

td.serial {
    padding: 15px 0px;
    text-align: right;
    width: 20px;
}

.current-loan tbody tr {
     background: #bce2a5 !important;
}

.checkedout-elsewhere {
    padding: 15px;
    background: #e2bca5 !important;
    border: 1px solid #d2ac95;
}

.available {
    padding: 15px;
    background: #bce2a5 !important;
    border: 1px solid #acd295;
}

.section {
    margin: 25px 0px;
}

.section h3 {
    margin: 1em 0em 0.5em 0em;
}

body#plain div#alert0 {
    background-color: #eeecad !important;
    border: 1px solid #d2ac95;
}

</style>
